package cn.ycoz.cloud.windspeed.netty4;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


public class BusinessThreadUtil {

    private static final ExecutorService executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100000));//CPU核数4-10倍
    private static final Logger logger = LoggerFactory.getLogger(BusinessThreadUtil.class);
    private static final byte[] CONTENT = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};


    public static void doBusiness(ChannelHandlerContext ctx, Object msg) {
        //异步线程池处理
        executor.submit( () -> {
            if (msg instanceof HttpRequest) {
//                // 模拟交易处理阻塞超时
//                try {
//                    int millis = 5000;
//                    logger.info("业务线程休眠 {} ms ", millis);
//                    Thread.sleep(millis);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

                HttpRequest req = (HttpRequest) msg;
                boolean keepAlive = HttpUtil.isKeepAlive(req);
                FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
                response.headers().set("Content-Type", "text/plain");
                response.headers().setInt("Content-Length", response.content().readableBytes());
                if (!keepAlive) {
                    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                } else {
                    response.headers().set("Connection", "keep-alive");
                    ctx.writeAndFlush(response);
                }
            }
        });
    }
}
//---------------------
//作者：cj2580
//来源：CSDN
//原文：https://blog.csdn.net/cj2580/article/details/78134134
//版权声明：本文为博主原创文章，转载请附上博文链接！